package com.useeinfo.oa.open.api.maintainOrder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.AliJsonObjectCover;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.*;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.base.enums.ResourceTypeEnum;
import com.useeinfo.oa.modules.maintaining.biz.*;
import com.useeinfo.oa.modules.maintaining.entity.*;
import com.useeinfo.oa.modules.maintaining.enums.InputTypeEnum;
import com.useeinfo.oa.modules.maintaining.enums.OrderOperationEnum;
import com.useeinfo.oa.modules.maintaining.enums.OrderStatusEnum;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.biz.UserDeviceBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/api/mobile/facilityMaintainSnap")
public class FacilityMaintainSnapAPI {
    @Autowired
    private FacilityMaintainSnapBiz facilityMaintainSnapBiz;
    @Autowired
    private FacilityBiz facilityBiz;
    @Autowired
    private MaintainPartnerBiz maintainPartnerBiz;
    @Autowired
    private FacilityCatBiz facilityCatBiz;
    @Autowired
    private MaintainTechnologyBiz maintainTechnologyBiz;
    @Autowired
    private MaintainOrderWorkContentBiz maintainOrderWorkContentBiz;
    @Autowired
    private ResourceBiz resourceBiz;
    @Autowired
    private MaintainOrderBiz maintainOrderBiz;
    @Autowired
    private OrganizationBiz organizationBiz;
    @Autowired
    private SystemUserBiz systemUserBiz;
    @Autowired
    private PositionBiz positionBiz;
    @Autowired
    private MaintainOrderLogBiz maintainOrderLogBiz;
    @Autowired
    private WorkingHoursBiz workingHoursBiz;
    @Autowired
    private UserDeviceBiz userDeviceBiz;
    @Autowired
    private PlanMessageSendBiz planMessageSendBiz;

    /**
     * 获取新增一次性维保单时的临时设备列表
     */
    @RequestMapping(value = "/getFacilityMaintainSnapList")
    public ResultDto getFacilityMaintainSnapList(@RequestParam(value = "serial", required = false) String serial,
                                                 @RequestParam(value = "maintainOrderId", required = false) String maintainOrderId,
                                                 HttpServletRequest request) {
        if (StringUtils.isEmpty(serial)) {
            return ResultUtil.error("参数异常");
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("serial", serial);
        if (StringUtils.isNotEmpty(maintainOrderId)) {
            queryParam.getSqlMap().put("maintainOrderId", maintainOrderId);
        }
        List<FacilityMaintainSnap> facilityMaintainSnapList = facilityMaintainSnapBiz.findList(queryParam);
        JSONArray array = new JSONArray();
        for (FacilityMaintainSnap facilityMaintainSnap : facilityMaintainSnapList) {
            JSONObject json = new JSONObject();
            json.put("id", facilityMaintainSnap.getId());
            json.put("facilityId", facilityMaintainSnap.getFacilityId());
            json.put("facilityName", facilityMaintainSnap.getFacilityName());
            json.put("facilityCode", facilityMaintainSnap.getFacilityCode());
            json.put("rootCatName", facilityMaintainSnap.getRootCatName());
            json.put("facilityCatName", facilityMaintainSnap.getFacilityCatName());
            json.put("areaName", facilityMaintainSnap.getAreaName());
            json.put("position", facilityMaintainSnap.getPosition());
            json.put("fieldPhotoPath", facilityMaintainSnap.getFieldPhotoPath());
            json.put("QRCode", facilityMaintainSnap.getQRCode());
            json.put("maintainId", facilityMaintainSnap.getMaintainId());
            array.add(json);
        }
        return ResultUtil.success(array);
    }

    /**
     * 添加设备(新增一次性维保单时)
     */
    @RequestMapping(value = "/addFacility")
    public ResultDto addFacility(@RequestParam(value = "serial", required = false) String serial,
                                 @RequestParam(value = "facilityId", required = false) String facilityId,
                                 HttpServletRequest request) {
        if (StringUtils.isEmpty(serial) || StringUtils.isEmpty(facilityId)) {
            return ResultUtil.error("参数异常");
        }
        Facility facility = facilityBiz.findModel(StringConverters.ToLong(facilityId));
        if (facility == null) {
            return ResultUtil.error("无此设备");
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (facility.getEnterprise() != enterprise) {
            return ResultUtil.error("设备权限异常");
        }
        FacilityMaintainSnap facilityMaintainSnap = new FacilityMaintainSnap();
        facilityMaintainSnap.setSerial(serial);
        facilityMaintainSnap.setFacilityId(facility.getId());
        facilityMaintainSnap.setFacilityCode(facility.getCode());
        facilityMaintainSnap.setFacilityName(facility.getName());
        if (facility.getArea() != null) {
            facilityMaintainSnap.setAreaId(facility.getArea().getId());
            facilityMaintainSnap.setAreaName(facility.getArea().getAreaName());
        }
        if (facility.getFacilityCat() != null) {
            facilityMaintainSnap.setFacilityCatId(facility.getFacilityCat().getId());
            facilityMaintainSnap.setFacilityCatName(facility.getFacilityCat().getCatName());
            FacilityCat rootCat = facilityCatBiz.findRootCat(facility.getFacilityCat().getId());
            facilityMaintainSnap.setRootCatId(rootCat.getId());
            facilityMaintainSnap.setRootCatName(rootCat.getCatName());
        }
        facilityMaintainSnap.setPosition(facility.getPosition());
        facilityMaintainSnap.setPrecisePosition(facility.getPrecisePosition());
        //现场照片
        if (facility.getFieldPhoto() != null && facility.getFieldPhoto().size() != 0) {
            List<Resource> resourceList = new ArrayList<Resource>(facility.getFieldPhoto());
            facilityMaintainSnap.setFieldPhotoPath(StringConverters.null2String(resourceList.get(0).getPath()));
        }
        if (facility.getFacilityGroup() != null) {
            facilityMaintainSnap.setFacilityGroupId(facility.getFacilityGroup().getId());
            facilityMaintainSnap.setFacilityGroupName(facility.getFacilityGroup().getFacilityGroupName());
            facilityMaintainSnap.setFacilityGroupCode(facility.getFacilityGroup().getFacilityGroupCode());
        }
        facilityMaintainSnap.setQRCode(facility.getQrCode());
        facilityMaintainSnapBiz.addOrUpdate(facilityMaintainSnap);
        return ResultUtil.success();
    }

    /**
     * 添加工艺(新增一次性维保单时)
     */
    @RequestMapping(value = "/addTechnology")
    public ResultDto addTechnology(@RequestParam(value = "facilityMaintainSnapId", required = false) String facilityMaintainSnapId,
                                   @RequestParam(value = "maintainTechnologyId", required = false) String maintainTechnologyId,
                                   HttpServletRequest request) {
        if (StringUtils.isEmpty(facilityMaintainSnapId) || StringUtils.isEmpty(maintainTechnologyId)) {
            return ResultUtil.error("参数异常");
        }
        FacilityMaintainSnap facilityMaintainSnap = facilityMaintainSnapBiz.findModel(StringConverters.ToLong(facilityMaintainSnapId));
        MaintainTechnology maintainTechnology = maintainTechnologyBiz.findModel(StringConverters.ToLong(maintainTechnologyId));
        if (facilityMaintainSnap == null || maintainTechnology == null) {
            return ResultUtil.error("参数异常");
        }
        if (!maintainTechnology.getFacilityCat().getId().equals(facilityMaintainSnap.getFacilityCatId())) {
            return ResultUtil.error("设备无法选择此工艺");
        }
        facilityMaintainSnap.setMaintainId(maintainTechnology.getId());
        facilityMaintainSnap.setMaintainName(maintainTechnology.getName());
        facilityMaintainSnap.setSpec(maintainTechnology.getSafetyRequirement());
        facilityMaintainSnapBiz.addOrUpdate(facilityMaintainSnap);
        return ResultUtil.success();
    }

    /**
     * 设备维保内容的临时保存(单个设备)
     */
    @RequestMapping(value = "/singleSnapTemporarySave")
    public ResultDto singleSnapTemporarySave(@RequestParam(value = "temporaryData", required = false) String temporaryData,
                                             @RequestParam(value = "facilityMaintainSnapId", required = false) String facilityMaintainSnapId,
                                             HttpServletRequest request) {
        JSONObject results = new JSONObject();
        if (StringUtils.isBlank(facilityMaintainSnapId) || StringUtils.isBlank(temporaryData)) {
            return ResultUtil.error("参数异常");
        }
        FacilityMaintainSnap facilityMaintainSnap = facilityMaintainSnapBiz.findModel(StringConverters.ToLong(facilityMaintainSnapId));
        if (facilityMaintainSnap == null) {
            return ResultUtil.error("参数异常");
        }
        MaintainOrder maintainOrder = facilityMaintainSnap.getMaintainOrder();
        if (maintainOrder == null) {
            return ResultUtil.error("参数异常");
        }
        JSONArray jsonArray = JSONArray.parseArray(temporaryData);
        JSONArray resultArray = new JSONArray();
        JSONArray applicationArray = new JSONArray();
        Long applicationId = null;//默认应用场景ID
        if (jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject resultObject = new JSONObject();
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String maintainOrderWorkContentId = jsonObject.getString("maintainOrderWorkContentId");//维保内容ID
                String result = jsonObject.getString("result");//输入内容
                JSONArray photoArray = jsonObject.getJSONArray("photoPath");
                String abnormal = jsonObject.getString("abnormal");//执行结果
                applicationId = StringConverters.ToLong(jsonObject.getString("applicationId"));//当前的应用场景ID
                MaintainOrderWorkContent maintainOrderWorkContent = maintainOrderWorkContentBiz.findModel(StringConverters.ToLong(maintainOrderWorkContentId));
                if (maintainOrderWorkContent == null) {
                    continue;
                }

                maintainOrderWorkContent.setResult(result);
                maintainOrderWorkContent.setContentPhoto(null);
                if (StringUtils.isNotBlank(abnormal)) {
                    maintainOrderWorkContent.setAbnormal(Boolean.parseBoolean(abnormal));
                }
                if (photoArray != null && photoArray.size() > 0) {
                    Set<Resource> resourceSet = new HashSet<>();
                    for (int j = 0; j < photoArray.size(); j++) {
                        String path = StringConverters.null2String(photoArray.getString(j));
                        if (StringUtils.isNotBlank(path)) {
                            Resource resource = new Resource();
                            resource.setResourceTypeEnum(ResourceTypeEnum.IMG);
                            resource.setPath(path);
                            resource.setResourceName("维保内容照片");
                            resourceBiz.addOrUpdate(resource);
                            resourceSet.add(resource);
                        }
                    }
                    maintainOrderWorkContent.setContentPhoto(resourceSet);
                }
                if (StringUtils.isNotBlank(result) || photoArray != null ||"尚未选择".equals(result)) {
                    maintainOrderWorkContent.setFinishTime(new Date());
                }
                maintainOrderWorkContentBiz.addOrUpdate(maintainOrderWorkContent);
                //2019-01-21 Sheaodn增加返回值
                resultObject.put("inputTypeEnum", StringConverters.null2String(maintainOrderWorkContent.getInputTypeEnum().getCode()));
                if (InputTypeEnum.COMPLETE_TYPE.getCode().equals(maintainOrderWorkContent.getInputTypeEnum().getCode()) || InputTypeEnum.STATUS_TYPE.getCode().equals(maintainOrderWorkContent.getInputTypeEnum().getCode())) {
                    String[] names = maintainOrderWorkContent.getInputTypeEnum().getName().split("、");
                    JSONArray nameArray = new JSONArray();
                    nameArray.addAll(Arrays.asList(names));
                    resultObject.put("inputType", nameArray);
                } else {
                    resultObject.put("inputType", StringConverters.null2String(maintainOrderWorkContent.getInputTypeEnum().getName()));
                }
                resultObject.put("contentId", StringConverters.null2Long(maintainOrderWorkContent.getId()));
                resultObject.put("unit", StringConverters.null2String(maintainOrderWorkContent.getUnit()));
                resultObject.put("applicationId", StringConverters.null2Long(maintainOrderWorkContent.getApplication_scenarios_id()));
                resultObject.put("applicationName", StringConverters.null2String(maintainOrderWorkContent.getApplication_scenarios_name()));
                resultObject.put("photo", StringConverters.null2Boolean(maintainOrderWorkContent.getPhoto()));
                resultObject.put("maxNumber", StringConverters.null2Double(maintainOrderWorkContent.getMaxNumber()));
                resultObject.put("minNumber", StringConverters.null2Double(maintainOrderWorkContent.getMinNumber()));
                resultObject.put("abnormal", StringConverters.null2Boolean(maintainOrderWorkContent.getAbnormal()));
                resultObject.put("name", StringConverters.null2String(maintainOrderWorkContent.getName()));
                resultObject.put("content", StringConverters.null2String(maintainOrderWorkContent.getContent()));
                JSONArray array = new JSONArray();
                if(StringUtils.isNotBlank(maintainOrderWorkContent.getContent())){
                    array = JSONArray.parseArray(maintainOrderWorkContent.getContent());
                }
                resultObject.put("contentArray", array);
                resultObject.put("category", StringConverters.null2String(maintainOrderWorkContent.getCategory()));
                resultObject.put("result", StringConverters.null2String(maintainOrderWorkContent.getResult()));
                resultObject.put("photos", photoArray);
                String pdfPath = "";
                if (StringUtils.isNotBlank(maintainOrderWorkContent.getResourceIds())) {
                    Resource resource = resourceBiz.findModel(StringConverters.ToLong(maintainOrderWorkContent.getResourceIds()));
                    if (resource != null) {
                        pdfPath = resource.getPath();
                    }
                }
                resultObject.put("resources", pdfPath);
                resultArray.add(resultObject);
            }
        }
        //更新该设备的默认应用场景ID
        if(applicationId!=null){
            facilityMaintainSnap.setApplicationScenariosId(applicationId);
            facilityMaintainSnapBiz.addOrUpdate(facilityMaintainSnap);
        }
        //更新百分比(以及工单是否异常 以及更新maintainOrder表工时字段)
        maintainOrderBiz.updatePercent(maintainOrder.getId() + "");
        facilityMaintainSnap = facilityMaintainSnapBiz.findModel(StringConverters.ToLong(facilityMaintainSnapId));
        //操作日志
        maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.TEMP_SUBMIT_ORDER, request);
        results.put("contents", resultArray);
        //查询applicationArray
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("facilityMaintainSnapId", facilityMaintainSnapId);
        List<MaintainOrderWorkContent> maintainOrderWorkContentList = maintainOrderWorkContentBiz.findList(queryParam);
        if (CollectionUtils.isNotEmpty(maintainOrderWorkContentList)) {
            for (MaintainOrderWorkContent maintainOrderWorkContent : maintainOrderWorkContentList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("applicationId", maintainOrderWorkContent.getApplication_scenarios_id());
                jsonObject.put("applicationName", maintainOrderWorkContent.getApplication_scenarios_name());
                if (!applicationArray.contains(jsonObject)) {
                    applicationArray.add(jsonObject);
                }
            }

        }
        results.put("applicationArray", applicationArray);
        results.put("facilityCode", facilityMaintainSnap.getFacilityCode());
        results.put("facilityId", facilityMaintainSnap.getId());
        results.put("applicationId", facilityMaintainSnap.getApplicationScenariosId()==null?"":facilityMaintainSnap.getApplicationScenariosId());
        results.put("facilityName", facilityMaintainSnap.getFacilityName());
        results.put("maintainName", facilityMaintainSnap.getMaintainName());
        results.put("spec", facilityMaintainSnap.getSpec());
        results.put("completed", facilityMaintainSnap.isCompleted());
        results.put("snapId", facilityMaintainSnap.getId());
        return ResultUtil.success(results);
    }

    /**
     * 设备维保内容的临时保存(多个)
     */
    @RequestMapping(value = "/temporarySave")
    public ResultDto temporarySave(@RequestParam(value = "temporaryData", required = false) String temporaryData,
                                   @RequestParam(value = "maintainOrderId", required = false) String maintainOrderId,
                                   @RequestParam(value = "userId", required = false) String userId,
                                   @RequestParam(value = "workingHours", required = false) String workingHoursString,
                                   HttpServletRequest request) {
        if (StringUtils.isBlank(maintainOrderId) || StringUtils.isBlank(temporaryData)) {
            return ResultUtil.error("参数异常");
        }
        MaintainOrder maintainOrder = maintainOrderBiz.findModel(StringConverters.ToLong(maintainOrderId));
        if (maintainOrder == null) {
            return ResultUtil.error("参数异常");
        }
        JSONArray jsonArray = JSONArray.parseArray(temporaryData);
        List<String> facilityMaintainSnapIds = new ArrayList<>();
        if (jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String facilityMaintainSnapId = jsonObject.getString("facilityMaintainSnapId");//维保设备ID
                String maintainOrderWorkContentId = jsonObject.getString("maintainOrderWorkContentId");//维保内容ID
                String result = jsonObject.getString("result");//输入内容
                JSONArray photoArray = jsonObject.getJSONArray("photoPath");
                String abnormal = jsonObject.getString("abnormal");//执行结果
                //保存该设备下的当前应用场景
                Long applicationId = StringConverters.ToLong(jsonObject.getString("applicationId"));//当前的应用场景ID
                FacilityMaintainSnap facilityMaintainSnap = facilityMaintainSnapBiz.findModel(StringConverters.ToLong(facilityMaintainSnapId));
                if(facilityMaintainSnap!=null){
                    facilityMaintainSnap.setApplicationScenariosId(applicationId);
                    facilityMaintainSnapBiz.addOrUpdate(facilityMaintainSnap);
                }

                if (!facilityMaintainSnapIds.contains(facilityMaintainSnapId)) {
                    facilityMaintainSnapIds.add(facilityMaintainSnapId);
                }
                MaintainOrderWorkContent maintainOrderWorkContent = maintainOrderWorkContentBiz.findModel(StringConverters.ToLong(maintainOrderWorkContentId));
                if (maintainOrderWorkContent == null) {
                    continue;
                }
                maintainOrderWorkContent.setResult(result);
                maintainOrderWorkContent.setContentPhoto(null);
                if (StringUtils.isNotBlank(abnormal)) {
                    maintainOrderWorkContent.setAbnormal(Boolean.parseBoolean(abnormal));
                }
                if (photoArray != null && photoArray.size() > 0) {
                    Set<Resource> resourceSet = new HashSet<>();
                    for (int j = 0; j < photoArray.size(); j++) {
                        String path = StringConverters.null2String(photoArray.getString(j));
                        if (StringUtils.isNotBlank(path)) {
                            Resource resource = new Resource();
                            resource.setResourceTypeEnum(ResourceTypeEnum.IMG);
                            resource.setPath(path);
                            resource.setResourceName("维保内容照片");
                            resourceBiz.addOrUpdate(resource);
                            resourceSet.add(resource);
                        }
                    }
                    maintainOrderWorkContent.setContentPhoto(resourceSet);
                }
                if (StringUtils.isNotBlank(result) || photoArray != null) {
                    maintainOrderWorkContent.setFinishTime(new Date());
                }
                maintainOrderWorkContentBiz.addOrUpdate(maintainOrderWorkContent);
            }
        }

        //更新百分比(以及工单是否异常 以及更新maintainOrder表工时字段)
        maintainOrderBiz.updatePercent(maintainOrderId);
        //操作日志
        maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.TEMP_SUBMIT_ORDER, request);
        //返回最新的内容
        ResultDto resultDto = maintainOrderBiz.detail(maintainOrderId);
        JSONObject obj = (JSONObject) resultDto.getData();
        JSONObject result = new JSONObject();
        JSONArray unfinished = new JSONArray();
        unfinished = obj.getJSONArray("unfinished");
        JSONArray finished = new JSONArray();
        finished = obj.getJSONArray("finished");
        result.put("unfinished", unfinished);
        result.put("finished", finished);
        return ResultUtil.success(result);
    }


    /**
     * 提交工单
     */
    @RequestMapping(value = "/submitOrder")
    public ResultDto submitOrder(@RequestParam(value = "maintainOrderId", required = false) String maintainOrderId,
                                 @RequestParam(value = "participantInputs", required = false) String participantInputs,
                                 HttpServletRequest request) {
        MaintainOrder maintainOrder = maintainOrderBiz.findModel(StringConverters.ToLong(maintainOrderId));
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser systemUser=SessionKeyUtils.getSessionUser(request);
        if (maintainOrder == null) {
            return ResultUtil.error("参数异常");
        }
        if (maintainOrder.getCancel() || maintainOrder.getDelay() || maintainOrder.isAuditing()) {
            return ResultUtil.error("该工单正在审核中，无法提交");
        }
        //查询所有snap 如果都是完成状态 则可以提交工单
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("maintainOrderId", maintainOrderId);
        List<FacilityMaintainSnap> facilityMaintainSnapList = facilityMaintainSnapBiz.findList(queryParam);
        boolean status = true;
        for (FacilityMaintainSnap facilityMaintainSnap : facilityMaintainSnapList) {
            if (!facilityMaintainSnap.isCompleted()) {
                status = false;
                break;
            }
        }
        if (!status) {
            return ResultUtil.error("工单未完成，无法提交");
        }

        List<Long> ids = new ArrayList<>();
        String auditAuthority = "ROLE_ENTERPRISE_MAINTAINING_MAINTAIN_AUDIT_ORDER";

        if (maintainOrder.getAuditCompleteID() != null) {

            JSONArray jsonArray = JSONArray.parseArray(maintainOrder.getCompleteFlow());
            if (jsonArray != null && jsonArray.size() > 0) {
                maintainOrder.setOrderStatusEnum(OrderStatusEnum.IN_AUDITING);
                maintainOrder.setLevel(1);
                if (jsonArray.size() == 1) {
                    maintainOrder.setAuditLast(true);
                } else {
                    maintainOrder.setAuditFirst(true);
                }
                maintainOrder.setAuditing(true);
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                Long organizationId = jsonObject.getLong("organizationId");
                Organization organization = organizationBiz.findModel(organizationId);
                maintainOrder.setOrganization(organization);
                String nodeTypeEnum = jsonObject.getString("nodeTypeEnum");
                Long relationId = jsonObject.getLong("relationId");
                if (nodeTypeEnum.equals("USER")) {
                    SystemUser user = systemUserBiz.findModel(relationId);
                    maintainOrder.setAuditSystemUser(user);
                    ids.add(user.getId());
                } else {
                    Position position = positionBiz.findModel(relationId);
                    maintainOrder.setPosition(position);
                    ids.addAll(systemUserBiz.getUserIdsByPosition(relationId.toString(),organizationId.toString(),enterprise.getId()+""));
                }
                if(!ids.contains(maintainOrder.getReceiveUser().getId())){
                    ids.add(maintainOrder.getReceiveUser().getId());//工单人也需要消息推送
                }
                //消息推送
                String content = "维保单:" + maintainOrder.getOrderCode() + "已完成,等待审核!";
                planMessageSendBiz.senMsg(maintainOrder.getId(),"maintain",maintainOrder.getEnterprise(),ids,content);


            } else {
                maintainOrder.setOrderStatusEnum(OrderStatusEnum.COMPLETED);
            }

        } else {
            maintainOrder.setOrderStatusEnum(OrderStatusEnum.COMPLETED);
        }
        maintainOrder.setPercent(100);
        maintainOrder.setFinishTime(new Date());
        maintainOrder.setCompleteUser(systemUser);
        maintainOrder.setComplete(true);
        //负责人工时计算
        long thisHours=DateTimeUtils.newGetDiffMinutesTime(DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss", DateTimeUtils.format(maintainOrder.getPresenceTime(), "yyyy-MM-dd HH:mm:ss")), new Date());
        maintainOrder.setWorkingHours(maintainOrder.getWorkingHours()+thisHours);
        //参与人工时计算
        long totalWorkingHours=0;
        JSONArray participantInputsArray = JSON.parseArray(participantInputs);
        if (participantInputsArray.size() > 0) {
            for (int i = 0; i < participantInputsArray.size(); i++) {
                JSONObject j = participantInputsArray.getJSONObject(i);
                Long workingHours = AliJsonObjectCover.ObjectLong(j, "workingHours");
                if (workingHours == null) {
                    return ResultUtil.error("工时不能为空！");
                }
                Long partnerId = AliJsonObjectCover.ObjectLong(j, "userId");
                QueryParam q = new QueryParam();
                q.getSqlMap().put("partnerId", partnerId == null ? "-1" : partnerId + "");
                q.getSqlMap().put("maintainOrderId", maintainOrder.getId() + "");
                q.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
                List<MaintainPartner> maintainPartnerList = maintainPartnerBiz.findList(q);
                if (CollectionUtils.isEmpty(maintainPartnerList)) {
                    return ResultUtil.error("参与人不存在！");
                }
                MaintainPartner maintainPartner = maintainPartnerList.get(0);
                totalWorkingHours+=workingHours;
                maintainPartner.setWorkingHours(maintainPartner.getWorkingHours() + workingHours);
                maintainPartnerBiz.addOrUpdate(maintainPartner);
            }
        }
        maintainOrder.setTotalWorkingHours(maintainOrder.getTotalWorkingHours()+thisHours+totalWorkingHours+totalWorkingHours);
        maintainOrderBiz.addOrUpdate(maintainOrder);
        //更新百分比(以及工单是否异常 以及更新maintainOrder表工时字段)
        maintainOrderBiz.updatePercent(maintainOrderId);

        //操作日志
        maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.SUBMIT_ORDER, request);


        return ResultUtil.success();
    }
}
